package com.ruoyi.project.WxMoudle.api;

import com.google.common.collect.Maps;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.interceptor.annotation.IgnoreAuth;
import com.ruoyi.project.WebMoudle.ImgFiles.domain.ImgFiles;
import com.ruoyi.project.WebMoudle.ImgFiles.service.IImgFilesService;
import com.ruoyi.project.WebMoudle.ShopSuser.domain.ShopSuser;
import com.ruoyi.project.WebMoudle.ShopSuser.domain.ShopVo;
import com.ruoyi.project.WebMoudle.ShopSuser.service.IShopSuserService;
import com.ruoyi.project.WebMoudle.UserCollect.domain.UserCollect;
import com.ruoyi.project.WebMoudle.UserCollect.service.IUserCollectService;
import com.ruoyi.project.WebMoudle.WxShop.domain.QueryShop;
import com.ruoyi.project.WebMoudle.WxShop.domain.WxShop;
import com.ruoyi.project.WebMoudle.WxShop.service.IWxShopService;
import com.ruoyi.project.WebMoudle.WxUser.domain.WxUser;
import com.ruoyi.project.WebMoudle.WxUser.service.IWxUserService;
import com.ruoyi.project.WebMoudle.advShow.domain.AdvDistance;
import com.ruoyi.project.WebMoudle.belongBank.domain.BelongBank;
import com.ruoyi.project.WebMoudle.belongBank.service.IBelongBankService;
import com.ruoyi.project.WebMoudle.shopCarouse.service.IShopCarouselService;
import com.ruoyi.project.WebMoudle.shopMessage.domain.ShopMessage;
import com.ruoyi.project.WebMoudle.shopMessage.service.IShopMessageService;
import com.ruoyi.project.WebMoudle.shopPick.domain.ShopPick;
import com.ruoyi.project.WebMoudle.shopPick.service.IShopPickService;
import com.ruoyi.project.WebMoudle.streamShop.domain.StreamShop;
import com.ruoyi.project.WebMoudle.streamShop.service.IStreamShopService;
import com.ruoyi.project.WebMoudle.streamTerrace.domain.StreamTerrace;
import com.ruoyi.project.WebMoudle.streamTerrace.service.IStreamTerraceService;
import com.ruoyi.project.WebMoudle.terraceDetail.domain.TerraceDetail;
import com.ruoyi.project.WebMoudle.terraceDetail.service.ITerraceDetailService;
import com.ruoyi.project.WebMoudle.useTerms.domain.UseTerms;
import com.ruoyi.project.WebMoudle.useTerms.service.IUseTermsService;
import com.ruoyi.project.WxMoudle.Bases.AppController;
import com.ruoyi.project.WxMoudle.Bases.WeixinConfig;
import com.ruoyi.project.WxMoudle.WebSocket.WebSocketServer;
import com.ruoyi.project.alipay.OtherUtils;
import com.ruoyi.project.pickToBC.RSAUtils;
import com.ruoyi.project.pickToBC.SendWeChat;
import com.ruoyi.project.pickToBC.WxBase64;
import com.ruoyi.project.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.security.PublicKey;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商户逻辑
 */
@RestController
@RequestMapping(value = "/wx/shop")
public class ShopController extends AppController {

    @Autowired
    private IWxUserService wxUserService;

    @Autowired
    private IImgFilesService imgFilesService;

    @Autowired
    private IWxShopService wxShopService;

    @Autowired
    private IShopSuserService shopSuserService;

    @Autowired
    private IShopCarouselService shopCarouselService;

    @Autowired
    private IUserCollectService userCollectService;

    @Autowired
    private IUserCollectService collectService;
    @Autowired
    private IShopPickService shopPickService;
    @Autowired
    private IBelongBankService belongBankService;

    @Autowired
    private IUseTermsService useTermsService;

    @Autowired
    private IStreamShopService streamShopService;
    @Autowired
    private IStreamTerraceService streamTerraceService;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private IShopMessageService shopMessageService;
    @Autowired
    private ITerraceDetailService terraceDetailService;
    /**
     * 商家申请
     */
    @RequestMapping(value = "/applyShop")
    @ResponseBody
    @IgnoreAuth
    public Object applyShop(@RequestParam(value = "SellImgss") MultipartFile[] SellImgss,
                            @RequestParam(value = "HeadImgss") MultipartFile[] HeadImgss,
                            WxShop shop) {
        if (StringUtils.isNull(shop.getWxUserId())){
            return toResponsFail("缺失用戶信息");
        }
        ShopVo wxShop =wxShopService.selectApplyShop(shop.getWxUserId());
        if (StringUtils.isNotNull(wxShop)){
            return toResponsFail("耐心等待上次的申请结果");
        }
        try {
            if (SellImgss != null) {//有营业执照
                for (MultipartFile file : SellImgss
                ) {
                    String upload = FileUploadUtils.upload(file);
                    ImgFiles img = new ImgFiles();
                    img.setImgName(file.getOriginalFilename());
                    img.setImgPath(upload);
                    imgFilesService.insertImgFiles(img);
                    if (StringUtils.isNotEmpty(shop.getShopSellImg())) {
                        //已有营业执照
                        shop.setShopSellImg(shop.getShopSellImg() + "," + img.getId());
                    } else {
                        shop.setShopSellImg(img.getId() + "");
                    }
                }
            } else {
                //没有营业执照
                return toResponsFail("缺少营业执照");
            }

            if (HeadImgss != null) {//有门头照
                for (MultipartFile file : HeadImgss
                ) {
                    String upload = FileUploadUtils.upload(file);
                    ImgFiles img = new ImgFiles();
                    img.setImgName(file.getOriginalFilename());
                    img.setImgPath(upload);
                    imgFilesService.insertImgFiles(img);
                    if (StringUtils.isNotEmpty(shop.getShopHeadImg())) {
                        //已有门头照
                        shop.setShopHeadImg(shop.getShopSellImg() + "," + img.getId());
                    } else {
                        shop.setShopHeadImg(img.getId() + "");
                    }
                }
            } else {
                //没有门头照
                return toResponsFail("缺少门头照");
            }
            int i = wxShopService.insertWxShop(shop);
            if (i > 0) {

                WxUser wxUser = wxUserService.selectWxUserById(shop.getWxUserId());
               // wxUser.setStatus("2");  //待审核中
                wxUserService.updateWxUser(wxUser);
                webSocketServer.sendAll("发送消息");
                return writeResultRep(wxUser, "等待审核");
            } else {
                return toResponsFail("申请失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return toResponsFail("申请失败");
        }
    }


    /**
     * 驳回后的再次申请
     */
    @RequestMapping(value = "/editShop")
    @ResponseBody
    @IgnoreAuth
    public Object editShop(@RequestParam(value = "SellImgss") MultipartFile[] SellImgss,
                           @RequestParam(value = "HeadImgss") MultipartFile[] HeadImgss,
                           WxShop ws) {
        WxShop wxShop = wxShopService.selectWxShopById(ws.getId());
        if (wxShop.getIsValid().equals("0")){    //已提交审核
            return toResponsFail("耐心等待上次的申请结果");
        }
        if (wxShop.getIsValid().equals("1")){   //审核通过
            return toResponsFail("此商铺审核通过,请勿重复申请");
        }
        try {
            if (SellImgss != null) {//有营业执照
                for (MultipartFile file : SellImgss
                ) {
                    String upload = FileUploadUtils.upload(file);
                    ImgFiles img = new ImgFiles();
                    img.setImgName(file.getOriginalFilename());
                    img.setImgPath(upload);
                    imgFilesService.insertImgFiles(img);
                    if (StringUtils.isNotEmpty(ws.getShopSellImg())) {
                        //已有营业执照
                        ws.setShopSellImg(ws.getShopSellImg() + "," + img.getId());
                    } else {
                        ws.setShopSellImg(img.getId() + "");
                    }
                }
            } else {
                //没有营业执照
                return toResponsFail("缺少营业执照");
            }

            if (HeadImgss != null) {//有门头照
                for (MultipartFile file : HeadImgss
                ) {
                    String upload = FileUploadUtils.upload(file);
                    ImgFiles img = new ImgFiles();
                    img.setImgName(file.getOriginalFilename());
                    img.setImgPath(upload);
                    imgFilesService.insertImgFiles(img);
                    if (StringUtils.isNotEmpty(ws.getShopHeadImg())) {
                        //已有门头照
                        ws.setShopHeadImg(ws.getShopSellImg() + "," + img.getId());
                    } else {
                        ws.setShopHeadImg(img.getId() + "");
                    }
                }
            } else {
                //没有门头照
                return toResponsFail("缺少门头照");
            }
            ws.setIsValid("0");
            int i = wxShopService.updateWxShop(ws);
            if (i > 0) {
                WxUser wxUser = wxUserService.selectWxUserById(ws.getWxUserId());
                wxUser.setStatus("2");  //待审核中
                wxUserService.updateWxUser(wxUser);
                webSocketServer.sendAll("发送消息");
                return writeResultRep(wxUser, "等待审核");
            } else {
                return toResponsFail("申请失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return toResponsFail("申请失败");
        }
    }

    /**
     * 根据商铺id查询店铺信息
     *
     * @return
     */
    @RequestMapping(value = "/selectOneShop")
    @ResponseBody
    @IgnoreAuth
    public Object selectOneShop(Long shopId) {
        HashMap<String, Object> map = new HashMap<>();
        WxShop wxShop = wxShopService.selectWxShopById(shopId);
        int vipCount = wxUserService.selectVipCount(shopId);
        int collectCount = collectService.selectShopCount(shopId);
        map.put("wxShop", wxShop);
        map.put("vipCount", vipCount);
        map.put("collectCount", collectCount);
        return map;
    }


    /*根据店家微信用户id 来查询商铺是否名下已存在自己的商铺*/
    @RequestMapping(value = "/queryShopByUid")
    @ResponseBody
    @IgnoreAuth
    public Object queryShopByUid(Long wxUserId) {
        ShopVo shopVo = wxShopService.selectApplyShop(wxUserId);
        return shopVo;
    }

    /*根据微信用户id查询自己关联的商铺列表*/
    @RequestMapping(value = "/toShopListByWid")
    @ResponseBody
    @IgnoreAuth
    public Object toShopListByWid(Long wxUserId) {
        List<ShopVo> list = shopSuserService.toShopListByWid(wxUserId);
        return list;
    }

    /**
     * 根据shopId查询店铺信息
     *
     * @param shopId
     * @return
     */
    @RequestMapping(value = "/selectShopById")
    @ResponseBody
    @IgnoreAuth
    public Object selectShopById(Long shopId) {
        if (!StringUtils.isNotNull(shopId)) {
            return toResponsFail("添加失败");
        }

        WxShop wxShop = wxShopService.selectWxShopById(shopId);
        return writeResultRep(wxShop);
    }

    /**
     * 查询店铺的轮播图
     *
     * @param shopId
     * @return
     */
    @RequestMapping(value = "/selectShopCarouselByShopId")
    @ResponseBody
    @IgnoreAuth
    public Object selectShopCarouselByShopId(Long shopId) {

        List<String> list = shopCarouselService.selectShopCarouselByShopId(shopId);
        return list;
    }

    /**
     * 添加收藏
     *
     * @param shopId
     * @param userId
     * @return
     */
    @RequestMapping(value = "/saveCollect")
    @ResponseBody
    @IgnoreAuth
    public Object saveCollect(Long shopId, Long userId) {
        UserCollect userCollect = new UserCollect();
        userCollect.setUserId(userId);
        userCollect.setShopId(shopId);
        List<UserCollect> userCollects = userCollectService.selectUserCollectList(userCollect);
        if (userCollects.size()>0){
            return toResponsMsgSuccess("收藏成功");
        }else {
            userCollectService.insertUserCollect(userCollect);
        }
        return toResponsMsgSuccess("收藏成功");
    }

    /**
     * 取消收藏
     *
     * @param shopId
     * @param userId
     * @return
     */
    @RequestMapping(value = "/cancelCollect")
    @ResponseBody
    @IgnoreAuth
    public Object cancelCollect(Long shopId, Long userId) {
        UserCollect userCollect = new UserCollect();
        userCollect.setUserId(userId);
        userCollect.setShopId(shopId);
        List<UserCollect> userCollects = userCollectService.selectUserCollectList(userCollect);
        for (UserCollect collect : userCollects) {
            userCollectService.deleteUserCollectById(collect.getId());
        }
        return toResponsMsgSuccess("已取消收藏");
    }

    /**
     * 查询用户是否收藏此店铺
     *
     * @param shopId
     * @param userId
     * @return
     */
    @RequestMapping(value = "/selectSelfCollect")
    @ResponseBody
    @IgnoreAuth
    public Object selectSelfCollect(Long shopId, Long userId) {
        UserCollect userCollect = new UserCollect();
        userCollect.setUserId(userId);
        userCollect.setShopId(shopId);
        List<UserCollect> list = userCollectService.selectUserCollectList(userCollect);
        if (list.size() > 0) {
            return toResponsMsgSuccess("已收藏");
        }
        return toResponsFail("未收藏");
    }

    /**
     * 查询用户收藏列表
     *
     * @param userId
     * @param currentLng
     * @param currentLat
     * @return
     */
    @RequestMapping(value = "/queryMyList")
    @ResponseBody
    @IgnoreAuth
    public Object queryMyList(Long userId, String currentLng, String currentLat) {
        Map<Object, Object> map = new HashMap<>();
        List<UserCollect> list = userCollectService.queryMyList(userId, currentLng, currentLat);
        List<UseTerms> UseTerms = useTermsService.selectUseTermsList(null);
        BigDecimal returnRatio = UseTerms.get(0).getReturnRatio();
        map.put("list",list) ;
        map.put("returnRatio",returnRatio);
        return map;
    }

    /**
     * 查询商铺的会员列表
     *
     * @param shopId
     * @return
     */
    @RequestMapping(value = "/queryVipList")
    @ResponseBody
    @IgnoreAuth
    public Object queryVipList(Long shopId) {

        List<WxUser> list = wxUserService.queryVipList(shopId);
        return list;
    }
    /*查询店铺未读消息数量*/
    @RequestMapping(value = "/myMessageCount")
    @ResponseBody
    @IgnoreAuth
    public Object myMessageCount(Long shopId) {

        int i = shopMessageService.myMessageCount(shopId);
        return i;
    }
    /*查询消息列表*/
    @RequestMapping(value = "/queryMyMsgList")
    @ResponseBody
    @IgnoreAuth
    public Object queryMyMsgList(Long shopId) {

        List<ShopMessage> list = shopMessageService.queryMyMsgList(shopId);
        return list;
    }

    /*查询单一消息*/
    @RequestMapping(value = "/queryOneMsg")
    @ResponseBody
    @IgnoreAuth
    public Object queryOneMsg(Long smId) {
       ShopMessage shopMessage = shopMessageService.selectShopMessageById(smId);
        return shopMessage;
    }
    /*标记为已读*/
    @RequestMapping(value = "/markYiDu")
    @ResponseBody
    @IgnoreAuth
    public Object markYiDu(Long smId) {
       int i = shopMessageService.markYiDu(smId);
        return i;
    }

    /**
     * 关键字和输入条件搜索商铺
     *
     * @param queryShop
     * @return
     */
    @RequestMapping(value = "/querySomeShop")
    @ResponseBody
    @IgnoreAuth
    public Object querySomeShop(QueryShop queryShop) {
        Map<String, Object> map = new HashMap<>();
        List<AdvDistance> list = wxShopService.querySomeShop(queryShop);
        List<UseTerms> UseTerms = useTermsService.selectUseTermsList(null);
        BigDecimal returnRatio = UseTerms.get(0).getReturnRatio();
        map.put("list",list);
        map.put("returnRatio",returnRatio);
        return map;
    }

    /**
     * 商铺类型条件搜索人气高的商铺
     *
     * @param queryShop
     * @return
     */
    @RequestMapping(value = "/queryHotShopList")
    @ResponseBody
    @IgnoreAuth
    public Object queryHotShopList(QueryShop queryShop) {
        Map<String, Object> map = new HashMap<>();
        List<AdvDistance> list = wxShopService.queryHotShopList(queryShop);
        List<UseTerms> UseTerms = useTermsService.selectUseTermsList(null);
        BigDecimal returnRatio = UseTerms.get(0).getReturnRatio();
        map.put("list",list);
        map.put("returnRatio",returnRatio);
        return map;
    }

    /**
     * 根据商铺id查询余额
     *
     * @param shopId
     * @return
     */
    @RequestMapping(value = "/queryShopMoney")
    @ResponseBody
    @IgnoreAuth
    public Object queryShopMoney(Long shopId) {
        Map<Object, Object> map = new HashMap<>();
        WxShop wxShop = wxShopService.selectWxShopById(shopId);
        UseTerms useTerms = useTermsService.selectUseTermsList(null).get(0);
        map.put("shopMoney",wxShop.getShopMoney());
        map.put("shopAdded",useTerms.getShopAdded());
        map.put("shopSysId",wxShop.getWxUserId());
        if (useTerms.getStatus().equals("0")){
            map.put("isBuTie",true);
        }else {
            map.put("isBuTie",false);
        }
        return map;
    }

    /**
     * 商铺提现到零钱
     *
     * @param pickMoney       //提现金额
     * @param deductMoney     //扣除账户金额
     * @return
     */
    @RequestMapping(value = "/toPickWechat")
    @ResponseBody
    @IgnoreAuth
    @Transactional
    public Object toPickWechat(BigDecimal pickMoney, BigDecimal deductMoney,Long shopId) {
        if (!StringUtils.isNotNull(pickMoney) || !StringUtils.isNotNull(deductMoney) || !StringUtils.isNotNull(shopId)) {
            return writeResultFailure("缺少参数传递");
        }
        //商家账户扣除金额
        WxShop wxShop = wxShopService.selecShopMoneyById(shopId);  //查询商铺信息
        BigDecimal otherMoney = wxShop.getShopMoney().subtract(deductMoney);
        if (otherMoney.doubleValue()<0) {
            return writeResultFailure("余额不足");
        }
        //提现金额需要大于手续费
        UseTerms useTerms = useTermsService.selectUseTermsList(null).get(0);
        String str = "";
        String OrderNum = LocalDate.now().toString().replace("-", "") + LocalTime.now().toString().replace("-", "").replace(":", "").replace(".", "");
        try {
            /*进行提现*/
            WxUser wxUser = wxUserService.selectWxUserById(wxShop.getWxUserId());     //提现到商家老板账户
            str = toPickChange(pickMoney, wxUser.getOpenId(), OrderNum);    //提现到零钱
            if (str.equals("fail")){
                return writeResultFailure("提现失败");
            }
            //修改商铺余额
            wxShop.setShopMoney(otherMoney);
            wxShopService.updateWxShop(wxShop);
            //插入商家提现记录
            ShopPick shopPick = new ShopPick();
            shopPick.setBelongType("0");
            shopPick.setOrderNum(OrderNum);
            shopPick.setShopId(shopId);
            shopPick.setPickMoney(pickMoney);
            shopPick.setShopAdded(useTerms.getShopAdded());
            shopPickService.insertShopPick(shopPick);
            /*================插入流水表===================*/
            //1.平台流水
            StreamTerrace streamTerrace = new StreamTerrace();
            streamTerrace.setGainMoney(pickMoney.negate());
            streamTerrace.setGainType("商铺提现"+pickMoney+"元");
            streamTerrace.setOrderNum(OrderNum);
            streamTerrace.setHandleType("1");
            streamTerraceService.insertStreamTerrace(streamTerrace);
            useTermsService.updateTerraceMoney(pickMoney.negate());
            //2.店铺流水
            StreamShop streamShop = new StreamShop();
            streamShop.setShopId(shopId);
            streamShop.setStreamMoney(deductMoney.negate());
            streamShop.setStreamType("商铺提现"+pickMoney+"元");
            streamShop.setHandleType("1");
            streamShop.setOrderNum(OrderNum);
            streamShopService.insertStreamShop(streamShop);
            //3.额外手续费
            if (useTerms.getShopAdded().doubleValue()>0){
                TerraceDetail td = new TerraceDetail();
                td.setOperateMoney(useTerms.getShopAdded());
                td.setOperateType("3");   //额外手续费
                td.setHandleName(wxShop.getShopCompany());
                terraceDetailService.insertTerraceDetail(td);        //插入平台账单
            }

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return writeResultRep(otherMoney);
    }

    /**
     * 商家添加银行卡
     *
     * @param belongBank
     * @return
     */
    @RequestMapping(value = "/addShopBank")
    @ResponseBody
    @IgnoreAuth
    @Transactional
    public Object addShopBank(BelongBank belongBank) {
        belongBankService.insertBelongBank(belongBank);
        return writeResultRep();
    }

    /**
     * 商家银行卡列表
     *
     * @param belongBank
     * @return
     */
    @RequestMapping(value = "/queryShopBank")
    @ResponseBody
    @IgnoreAuth
    @Transactional
    public Object queryShopBank(BelongBank belongBank) {
        List<BelongBank> belongBanks = belongBankService.selectBelongBankList(belongBank);
        WxShop wxShop = wxShopService.selectWxShopById(belongBank.getBelongId());
        Map<String,Object> map =new HashMap();
        map.put("belongBanks",belongBanks);
        map.put("sysUserId",wxShop.getWxUserId());
        return map;
    }

    /**
     * 商家删除银行卡
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/deleteBank")
    @ResponseBody
    @IgnoreAuth
    @Transactional
    public Object deleteBank(Long bankId) {
        int i = belongBankService.deleteBelongBankById(bankId);
        if (i > 0) {
            return writeResultRep();
        }
        return writerResultFailure();
    }

    /**
     * 商家提现到银行卡    手续费和额外手续费未加入
     *
     * @param pickMoney   提现金额
     * @param deductMoney  扣除账户金额
     * @param  bankProcedure   手续费
     * @return
     */
    @RequestMapping(value = "/toPickBank")
    @ResponseBody
    @IgnoreAuth
    @Transactional
    public Object toPickBank(BigDecimal pickMoney, BigDecimal deductMoney,BigDecimal bankProcedure,Long shopId, Long bankId) {
        if (!StringUtils.isNotNull(pickMoney) || !StringUtils.isNotNull(shopId) || !StringUtils.isNotNull(bankId)) {
            return writeResultFailure("缺少参数传递");
        }
        //商家账户减去需要扣除的金额
        WxShop wxShop = wxShopService.selecShopMoneyById(shopId);     //查询商铺信息
        BigDecimal otherMoney = wxShop.getShopMoney().subtract(deductMoney);
        if (otherMoney.doubleValue()<0) {
            return writeResultFailure("余额不足");
        }
        //获取平台基本设置
        UseTerms useTerms = useTermsService.selectUseTermsList(null).get(0);
        BelongBank belongBank = belongBankService.selectBelongBankById(bankId);
        String str = "";
        String OrderNum = LocalDate.now().toString().replace("-", "") + LocalTime.now().toString().replace("-", "").replace(":", "").replace(".", "");
        try {
            str = wxCashBank(OrderNum, belongBank.getBankNum(), belongBank.getAccountName(), belongBank.getBankCode(), pickMoney);    //提现到银行卡
            if (str.equals("fail")){
                return writeResultFailure("提现失败");
            }
            //修改商铺余额
            wxShop.setShopMoney(otherMoney);
            wxShopService.updateWxShop(wxShop);     //修改商铺的余额
            //1.插入商铺提现记录
            ShopPick shopPick = new ShopPick();
            shopPick.setBelongType("1");
            shopPick.setOrderNum(OrderNum);
            shopPick.setShopId(shopId);
            shopPick.setPickMoney(pickMoney);
            shopPick.setAccountName(belongBank.getAccountName());
            shopPick.setBankCode(belongBank.getBankCode());
            shopPick.setBankNum(belongBank.getBankNum());
            shopPick.setShopAdded(useTerms.getShopAdded());
            //如果平台补贴手续费 则需要记录
            if (useTerms.getStatus().equals("0")){
                TerraceDetail terraceDetail = new TerraceDetail();
                terraceDetail.setOperateMoney(bankProcedure.negate());
                terraceDetail.setOperateType("4");   //平台补贴
                terraceDetail.setHandleName(wxShop.getShopCompany());
                terraceDetailService.insertTerraceDetail(terraceDetail);        //插入平台账单
                useTermsService.updateTerraceMoney(bankProcedure.negate());     //修改平台流动资金
            }else {
                shopPick.setPickCommission(bankProcedure);      //不补贴记录真实手续费（数据库默认为0）
            }
            shopPickService.insertShopPick(shopPick);     //商铺提现记录
            //插入流水表
            //1.平台流水
            StreamTerrace streamTerrace = new StreamTerrace();
            streamTerrace.setGainMoney(pickMoney.negate());
            streamTerrace.setGainType("商铺提现"+pickMoney+"元");
            streamTerrace.setOrderNum(OrderNum);
            streamTerrace.setHandleType("1");
            streamTerraceService.insertStreamTerrace(streamTerrace);
            useTermsService.updateTerraceMoney(pickMoney.negate());
            //2.店铺流水
            StreamShop streamShop = new StreamShop();
            streamShop.setShopId(shopId);
            streamShop.setStreamMoney(deductMoney.negate());
            streamShop.setOrderNum(OrderNum);
            streamShop.setStreamType("商铺提现"+pickMoney+"元");
            streamShop.setHandleType("1");
            streamShopService.insertStreamShop(streamShop);
            //3.额外手续费
            if (useTerms.getShopAdded().doubleValue()>0){
                TerraceDetail td = new TerraceDetail();
                td.setOperateMoney(useTerms.getShopAdded());
                td.setOperateType("3");   //额外手续费
                td.setHandleName(wxShop.getShopCompany());
                terraceDetailService.insertTerraceDetail(td);        //插入平台账单
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return writeResultRep(otherMoney);
    }

    /**
     * 查询商户的提现记录
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/queryMonthLog")
    @ResponseBody
    @IgnoreAuth
    @Transactional
    public Object queryMonthLog(Long shopId, String month) {
        if (!StringUtils.isNotNull(shopId) || !StringUtils.isNotEmpty(month)) {
            return writeResultFailure("缺少参数传递");
        }
        List<ShopPick> shopPicks = shopPickService.queryMonthLog(shopId, month);

        return writeResultRep(shopPicks);
    }


    /*==================================================静态方法的调用==========================================================================================*/
    /*提现到零钱的方法*/
    public String toPickChange(BigDecimal sumAmount, String openId, String OrderNum) throws Exception {

        //提现金额(单位:元)
        //元转换为分,微信支付已分为单位
        Map<String, String> map = Maps.newHashMap();
        //乘以100，转换为分
        BigDecimal transAmt = sumAmount.multiply(new BigDecimal("100"));

        //订单号
        map.put("partner_trade_no", OrderNum);
        map.put("mch_appid", WeixinConfig.APPID);
        map.put("mchid", WeixinConfig.MACHINEDID);
        map.put("check_name", "NO_CHECK");
        //随机字符串
        map.put("nonce_str", OtherUtils.getNonceStr().toString());
        map.put("spbill_create_ip", WeixinConfig.SPBILL_CREATE_IP);
        //openid("c从数据库中查询")
        map.put("openid", openId);
        //金额
        map.put("amount", Integer.toString(transAmt.intValue()));
        ////企业付款操作说明信息
        map.put("desc", "提现成功");

        //调用支付
        String returnInfo = SendWeChat.toWeChat(map, WeixinConfig.PAY_TO_PERON);
        Map<String, String> resultMap = OtherUtils.readStringXmlOut(returnInfo);
        if (resultMap.containsKey("result_code") && "SUCCESS".equals(resultMap.getOrDefault("result_code", ""))) {    //提现成功
            System.out.println("提现到零钱成功");
            System.out.println("返回结果：" + returnInfo);
            return "success";
        } else {
            if (resultMap.containsKey("err_code") && "SYSTEMERROR".equals(resultMap.get("err_code"))) {     //微信内部错误,重试一次
                System.out.println("微信内部错误,开始重试了");
                String res = SendWeChat.toWeChat(map, WeixinConfig.PAY_TO_PERON);
                Map<String, String> resMap = OtherUtils.readStringXmlOut(res);
                if (resMap.containsKey("result_code") && "SUCCESS".equals(resMap.getOrDefault("result_code", ""))) {
                    System.out.println("重试提现到零钱成功");
                    System.out.println("返回结果：" + res);
                    return "success";
                }
                return "fail";
            }
            System.out.println("提现到零钱失败");
            System.out.println("返回结果：" + returnInfo);
            return "fail";
        }

    }

    /*微信提现到个人银行卡*/
    public static String wxCashBank(String orderNum, String cardNum, String accountName, String bankCode, BigDecimal amout) throws Exception {

        String rsa = "RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING";
        PublicKey pub = RSAUtils.getPubKey(WeixinConfig.PUBLIC_PEM_PATH, "RSA"); //读取PKCS8密钥文件
        byte[] estr = RSAUtils.encrypt(cardNum.getBytes(), pub, 2048, 11, rsa);   //对银行账号进行加密
        String rscardNo = WxBase64.encode(estr);//并转为base64格式
        byte[] estr2 = RSAUtils.encrypt(accountName.getBytes(), pub, 2048, 11, rsa);   //对银行账号进行加密
        String rsaccountName = WxBase64.encode(estr2);//并转为base64格式

        HashMap<String, String> map = new HashMap<String, String>();
        BigDecimal transAmt = amout.multiply(new BigDecimal("100"));
        map.put("mch_id", WeixinConfig.MACHINEDID);  //商户号
        map.put("partner_trade_no", orderNum);//商户订单号（提现id)
        map.put("nonce_str", OtherUtils.getNonceStr().toString());      //随机字符串

        map.put("enc_bank_no", rscardNo);//收款方银行卡号
        map.put("enc_true_name", rsaccountName);//收款方用户名
        map.put("bank_code", bankCode);//收款方开户行id
        map.put("amount", Integer.toString(transAmt.intValue()));//上线后需要更改
        String projectName = "有有积分";
        map.put("desc", "【" + projectName + "】账户资金提现");
        String returnInfo = SendWeChat.toWeChat(map, WeixinConfig.PAY_TO_BANK);    //请求微信接口
        Map<String, String> resultMap = OtherUtils.readStringXmlOut(returnInfo);
        if (resultMap.containsKey("result_code") && "SUCCESS".equals(resultMap.getOrDefault("result_code", ""))) {  //提现成功
            System.out.println("提现到银行卡成功");
            System.out.println("返回结果：" + returnInfo);
            return "success";
        } else {
            if (resultMap.containsKey("err_code") && "SYSTEMERROR".equals(resultMap.get("err_code"))) {     //微信内部错误,重试一次
                System.out.println("微信内部错误,开始重试了");
                String res = SendWeChat.toWeChat(map, WeixinConfig.PAY_TO_BANK);
                Map<String, String> resMap = OtherUtils.readStringXmlOut(res);
                if (resMap.containsKey("result_code") && "SUCCESS".equals(resMap.getOrDefault("result_code", ""))) {
                    System.out.println("重试提现到银行卡成功");
                    System.out.println("返回结果：" + res);
                    return "success";
                }
                return "fail";
            }

            System.out.println("提现到银行卡失败");
            System.out.println("返回结果：" + returnInfo);
            return "fail";
        }
    }

    public static void main(String[] args) {
        BigDecimal bigDecimal = new BigDecimal("154").multiply(new BigDecimal("0.001")).setScale(2, BigDecimal.ROUND_HALF_DOWN);
        System.out.println(bigDecimal);
        System.out.println(bigDecimal.doubleValue()>0.1);
        String OrderNum = LocalDate.now().toString().replace("-", "") + LocalTime.now().toString().replace("-", "").replace(":", "").replace(".", "");

    }

}
